import uuid
from django.http import JsonResponse
from apps.order.models import BaseOrder, TeamInCome, TransferRecord, TransferErrorCode
from apps.product.models import Product
from core.tools.paginator import DjangoPaginator
from core.tools.wx_login_verify import wx_login
from core.wchat.wx_base import WxPay
from core.tools.wx_session import get_wx_session
from core.tools.get_ip import get_ip
from core.tools.FormatXmlArray import FormatXmlArray


@wx_login()
def sales_orders(request):
    """
    个人业绩， 我的订单
    :param request:
    :return:
    """
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    product_id = request.GET.get('p_id')
    is_close = request.GET.get("is_close")
    page = int(request.GET.get("page")) if request.GET.get("page") else 1
    order = BaseOrder.objects.filter(salesman=user_info)
    if product_id and product_id != "0":
        product_obj = Product.objects.get(id=product_id)
        if product_obj.sign_type == 4 or product_obj.product_set.all():
            product_queryset = product_obj.product_set.all()
            order1 = order.filter(product__in=product_queryset)
            order2 = order.filter(product_id=product_id)
            order = order1 | order2
        else:
            order = order.filter(product_id=product_id)
    if is_close:
        order = order.filter(is_close=is_close)
    order, page_dict = DjangoPaginator.get_paging(order, page=page)
    order_list = []
    for i in order:
        d = dict()
        d["name"] = i.single.applicant.name
        d["create_time"] = i.create_time.strftime("%Y-%m-%d")
        d["income"] = "%.2f" % i.income
        d["is_close"] = i.product.name  # i.get_is_close_display()
        order_list.append(d)
    content = {"order_list": order_list, "page_dict": page_dict}
    return JsonResponse(content)


@wx_login()
def sales_income(request):
    """
    业务员收入合计
    :param request:
    :return:
    """
    # is_close = 1 已提现  累计提现
    # is_close = 2 可提现
    # is_close = 3 待提现
    from finance_c2c.local_settings import ONLINE
    wx_obj = get_wx_session(request)
    user_info = wx_obj.salesman
    p_id = request.GET.get("ppk", None)
    self_income_content = BaseOrder.objects.sum_income(user_info, p_id=p_id)
    team_income_content = TeamInCome.objects.sum_income(user_info)
    content = self_income_content
    content["head_url"] = wx_obj.head_url
    content["nick_name"] = wx_obj.nick_name
    content["show_declaration"] = user_info.channel.show_declaration  # 是否显示免责声明
    content["sum_is_close_1"] = content["sum_is_close_1"] + team_income_content["sum_is_close_1"]
    if not ONLINE:
        content["sum_is_close_2"] = 20
    else:
        content["sum_is_close_2"] = content["sum_is_close_2"] + team_income_content["sum_is_close_2"]
    content["sum_is_close_3"] = content["sum_is_close_3"] + team_income_content["sum_is_close_3"]
    if request.session.has_key("scrfviews"):
        del request.session['scrfviews']
    scrfviews = uuid.uuid1()
    request.session["scrfviews"] = scrfviews
    print(request.session["scrfviews"])
    return JsonResponse(content)


@wx_login()
def transfer(request):
    if request.session.has_key("scrfviews"):
        pass
    else:
        content = {"status": "error", "msg": "网络异常请稍后重试"}
        return JsonResponse(content)
    wx_obj = get_wx_session(request)
    salesman = wx_obj.salesman
    if not salesman.can_transfer:
        content = {"status": "error", "msg": "不可提现"}
        return JsonResponse(content)
    del request.session['scrfviews']
    user_id = wx_obj.openid
    desc = "奖励金"
    check_name = "NO_CHECK"
    wx_pay = WxPay()
    # 判断
    if TransferRecord.objects.filter(salesman=salesman, is_over=False).exists():
        # 说明还有没处理完的订单
        content = {"status": "error", "msg": "还有未处理完的订单，请稍后再试"}
        return JsonResponse(content)
    else:
        # 参数
        self_order_id_list, self_amount = BaseOrder.objects.id_list_and_close_sum(salesman)
        team_order_id_list, team_amount = TeamInCome.objects.id_list_and_close_sum(salesman)
        self_order_id_list_str = [str(i) for i in self_order_id_list]
        team_order_id_list_str = [str(i) for i in team_order_id_list]
        amount = self_amount + team_amount
        if amount < 100:
            content = {"status": "error", "msg": "提现小于最小金额"}
            return JsonResponse(content)
        else:
            out_trade_no = wx_pay.out_trade_no
            nonce_str = wx_pay.nonce_str
            spbill_create_ip = get_ip(request)
            # 保存参数
            t_record = TransferRecord.objects.create(
                salesman=salesman,
                self_income='[' + ','.join(self_order_id_list_str) + ']',
                team_income='[' + ','.join(team_order_id_list_str) + ']',
                amount=amount,
                spbill_create_ip=spbill_create_ip,
                partner_trade_no=out_trade_no,
                nonce_str=nonce_str,
            )
            # 企业付款接口
            print(out_trade_no, "out_trade_no")
            try:
                info = wx_pay.transfer.transfer(user_id, amount, desc, check_name=check_name, out_trade_no=out_trade_no)
            except Exception as e:
                info = e.response.content
                info = FormatXmlArray.xml_to_array(info)
            info["again"] = False
            if info.get("return_code") == "SUCCESS":  # 通信code
                if info.get("result_code") == "SUCCESS":
                    info["again"] = False
                    t_error_code = TransferErrorCode.objects.create_data(info)
                else:
                    if info.get("err_code") == "SYSTEMERROR":
                        #  如果是系统错误 再重新发一次（同一个out_trade_no）
                        print(out_trade_no, "out_trade_no")
                        info = wx_pay.transfer.transfer(user_id, amount, desc, check_name=check_name,
                                                        out_trade_no=out_trade_no)
                        info["again"] = True
                        t_error_code = TransferErrorCode.objects.create_data(info)
                    else:
                        t_error_code = TransferErrorCode.objects.create_data(info)
            else:
                t_error_code = TransferErrorCode.objects.create_data(info)
            t_record.is_over = True
            t_record.error_code = t_error_code
            t_record.save()
            # 更新提现的数据
            if info.get("return_code") != "SUCCESS":
                content = {"status": "ok", "msg": "服务器错误,请在公众号中留言"}
                return JsonResponse(content)
            if info.get("result_code") == "SUCCESS":
                BaseOrder.objects.update_close(list(self_order_id_list))
                TeamInCome.objects.update_close(list(team_order_id_list))
                content = {"status": "ok", "msg": "提现成功，请在微信零钱里查看"}
            else:
                msg = t_error_code.err_code_des
                content = {"status": "error", "msg": "%s,请在公众号中留言" % msg}
    return JsonResponse(content)
